<template>
  <div class="model-detail">
    <!-- 模型基本信息 -->
    <div class="model-info-section">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="模型名称">{{ model.name }}</el-descriptions-item>
        <el-descriptions-item label="模型类型">{{ model.model_type_display || getTypeText(model.model_type) }}</el-descriptions-item>
        <el-descriptions-item label="算法">{{ model.algorithm_display || model.algorithm }}</el-descriptions-item>
        <el-descriptions-item label="版本">v{{ model.version }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(model.status)">
            {{ getStatusText(model.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="准确率">{{ model.accuracy ? (model.accuracy * 100).toFixed(2) + '%' : 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="精确率">{{ model.precision ? (model.precision * 100).toFixed(2) + '%' : 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="召回率">{{ model.recall ? (model.recall * 100).toFixed(2) + '%' : 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="F1分数">{{ model.f1_score ? (model.f1_score * 100).toFixed(2) + '%' : 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="创建者">{{ model.created_by || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(model.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(model.updated_at) }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ model.description || '暂无描述' }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 模型性能指标 -->
    <div class="performance-section">
      <h3>性能指标</h3>
      <el-row :gutter="20">
        <el-col :span="6" v-for="metric in performanceMetrics" :key="metric.key">
          <div class="metric-card">
            <div class="metric-icon" :style="{ color: metric.color }">
              <el-icon :size="24">
                <component :is="metric.icon" />
              </el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ metric.value }}</div>
              <div class="metric-label">{{ metric.label }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 模型文件信息 -->
    <div class="files-section">
      <h3>模型文件</h3>
      <el-table :data="modelFiles" stripe>
        <el-table-column prop="name" label="文件名" />
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="size" label="大小" width="100" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="downloadFile(row)">
              <el-icon><Download /></el-icon>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 训练历史 -->
    <div class="history-section">
      <h3>训练历史</h3>
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in trainingHistory"
          :key="index"
          :timestamp="item.timestamp"
          :type="item.type"
        >
          <div class="history-item">
            <h4>{{ item.title }}</h4>
            <p>{{ item.description }}</p>
            <div v-if="item.metrics" class="history-metrics">
              <el-tag v-for="(value, key) in item.metrics" :key="key" size="small">
                {{ key }}: {{ value }}
              </el-tag>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 操作按钮 -->
    <div class="actions-section">
      <el-button-group>
        <el-button type="primary" @click="$emit('train', model)">
          <el-icon><VideoPlay /></el-icon>
          重新训练
        </el-button>
        <el-button type="success" @click="$emit('evaluate', model)">
          <el-icon><DataAnalysis /></el-icon>
          模型评估
        </el-button>
        <el-button 
          v-if="model.status === 'completed'"
          type="warning" 
          @click="$emit('deploy', model)"
        >
          <el-icon><Upload /></el-icon>
          部署模型
        </el-button>
        <el-button @click="$emit('export', model)">
          <el-icon><Download /></el-icon>
          导出模型
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Download, VideoPlay, DataAnalysis, Upload,
  TrendCharts, CircleCheck, Warning, Monitor
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  model: {
    type: Object,
    required: true
  }
})

// Emits
defineEmits(['train', 'evaluate', 'deploy', 'export'])

// 计算属性
const performanceMetrics = computed(() => {
  const metrics = []

  // 准确率
  if (props.model.accuracy !== null && props.model.accuracy !== undefined) {
    metrics.push({
      key: 'accuracy',
      label: '准确率',
      value: `${(props.model.accuracy * 100).toFixed(2)}%`,
      color: '#67C23A',
      icon: 'CircleCheck'
    })
  }

  // 精确率
  if (props.model.precision !== null && props.model.precision !== undefined) {
    metrics.push({
      key: 'precision',
      label: '精确率',
      value: `${(props.model.precision * 100).toFixed(2)}%`,
      color: '#409EFF',
      icon: 'TrendCharts'
    })
  }

  // 召回率
  if (props.model.recall !== null && props.model.recall !== undefined) {
    metrics.push({
      key: 'recall',
      label: '召回率',
      value: `${(props.model.recall * 100).toFixed(2)}%`,
      color: '#E6A23C',
      icon: 'DataAnalysis'
    })
  }

  // F1分数
  if (props.model.f1_score !== null && props.model.f1_score !== undefined) {
    metrics.push({
      key: 'f1Score',
      label: 'F1分数',
      value: `${(props.model.f1_score * 100).toFixed(2)}%`,
      color: '#F56C6C',
      icon: 'Monitor'
    })
  }

  // 如果没有任何指标，显示默认提示
  if (metrics.length === 0) {
    metrics.push({
      key: 'no_metrics',
      label: '暂无指标',
      value: 'N/A',
      color: '#909399',
      icon: 'Warning'
    })
  }

  return metrics
})

// 模型文件
const modelFiles = computed(() => [
  {
    name: `${props.model.name}_model.pkl`,
    type: '模型文件',
    size: '2.5MB',
    updateTime: props.model.updateTime
  },
  {
    name: `${props.model.name}_config.json`,
    type: '配置文件',
    size: '1.2KB',
    updateTime: props.model.updateTime
  },
  {
    name: `${props.model.name}_metrics.json`,
    type: '指标文件',
    size: '856B',
    updateTime: props.model.updateTime
  }
])

// 训练历史
const trainingHistory = computed(() => [
  {
    timestamp: props.model.updateTime,
    type: 'success',
    title: '模型训练完成',
    description: '使用随机森林算法完成模型训练，性能指标达到预期',
    metrics: {
      '准确率': `${props.model.accuracy}%`,
      '训练时长': '15分30秒',
      '数据量': '10万条'
    }
  },
  {
    timestamp: '2024-01-12 10:30:00',
    type: 'primary',
    title: '开始模型训练',
    description: '配置训练参数，开始模型训练过程',
    metrics: {
      '学习率': '0.001',
      '批次大小': '32',
      '训练轮数': '100'
    }
  },
  {
    timestamp: props.model.createTime,
    type: 'info',
    title: '创建模型',
    description: '初始化模型配置和基本信息',
    metrics: null
  }
])

// 方法
const getStatusType = (status) => {
  const types = {
    draft: 'info',
    training: 'warning',
    trained: 'success',
    deployed: 'primary',
    failed: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    draft: '草稿',
    training: '训练中',
    trained: '训练完成',
    deployed: '已部署',
    failed: '训练失败'
  }
  return texts[status] || '未知'
}

const getTypeText = (type) => {
  const texts = {
    churn_prediction: '用户流失预测',
    purchase_prediction: '购买意向预测',
    recommendation: '商品推荐系统',
    user_segmentation: '用户行为分群',
    price_optimization: '动态价格优化',
    inventory_forecast: '库存预测',
    lifetime_value: '用户生命周期价值',
    fraud_detection: '欺诈检测',
    sentiment_analysis: '情感分析',
    conversion_optimization: '转化率优化'
  }
  return texts[type] || type
}

const formatDate = (dateString) => {
  if (!dateString) return 'N/A'
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const downloadFile = (file) => {
  ElMessage.success(`正在下载 ${file.name}...`)
}
</script>

<style scoped>
.model-detail {
  padding: 20px 0;
}

.model-info-section,
.performance-section,
.files-section,
.history-section,
.actions-section {
  margin-bottom: 30px;
}

.performance-section h3,
.files-section h3,
.history-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 12px;
}

.metric-card {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  height: 80px;
}

.metric-icon {
  margin-right: 12px;
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.metric-label {
  font-size: 12px;
  color: #606266;
}

.history-item h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.history-item p {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #606266;
}

.history-metrics {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.actions-section {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e6e8eb;
}
</style>
